// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package store

import (
	"os"
	"path"
	"time"

	"github.com/gofrs/flock"
	"github.com/kumose/errors"
	"github.com/kumose/kmopt/pkg/utils"
)

type localStore struct {
	root     string
	upstream string
	flock    *flock.Flock
}

func newLocalStore(root, upstream string) *localStore {
	return &localStore{
		root:     root,
		upstream: upstream,
		flock:    flock.New(path.Join(root, "lock")),
	}
}

// Begin implements the Store
func (s *localStore) Begin() (FsTxn, error) {
	return newLocalTxn(s)
}

// Returns the last modify time
func (s *localStore) last(filename string) (*time.Time, error) {
	fp := path.Join(s.root, filename)
	if utils.IsNotExist(fp) {
		return nil, nil
	}
	fi, err := os.Stat(fp)
	if err != nil {
		return nil, errors.Annotate(err, "Stat file")
	}
	mt := fi.ModTime()
	return &mt, nil
}

func (s *localStore) path(filename string) string {
	return path.Join(s.root, filename)
}

func (s *localStore) lock() error {
	return s.flock.Lock()
}

func (s *localStore) unlock() {
	// The unlock operation must success, otherwise the later operation will stuck
	if err := s.flock.Unlock(); err != nil {
		panic(errors.Annotate(err, "unlock filesystem failed"))
	}
}
